package com.rabbit.order.service;

import com.rabbit.order.domain.OrderVO;
import com.rabbit.order.domain.OrderDAO;
import com.rabbit.order.repository.OrderRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderRepository orderRepository;
    public String createOrder(OrderVO orderVO ,String userId){
        OrderDAO orderDAO = new OrderDAO();
        BeanUtils.copyProperties(orderVO, orderDAO);
        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();
        orderDAO.setOrderId(s);
        orderDAO.setOrderStatus("start");
        String message = userId + ":" + s;
        rabbitTemplate.convertAndSend("e.order","r.order",message);
        orderRepository.addOrder(orderDAO, userId);
        return s;
    }

    public List<OrderVO> getOrders(String userId){
        List<OrderDAO> orders = orderRepository.getOrders(userId);
        if(orders ==null){
            return  new ArrayList<>();
        }
        return orders.stream().map(item->{
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(item, orderVO);
            return orderVO;
        }).collect(Collectors.toList());
    }


    public String payOrder(OrderVO orderVO, String userId) {

        Boolean aBoolean = orderRepository.updateOrderSuc(orderVO.getOrderId(), userId);
        return  aBoolean?"suc":"error";
    }
}
